package servlet;

import bean.User;
import service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = "/login1")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取输入框中的用户账号和密码
        String userName = request.getParameter ("userName");
        System.out.println ("获取的用户账号为：" + userName);
        String passWord = request.getParameter ("passWord");
        System.out.println ("获取到的密码是：" + passWord);
        //创建UserServlet去验证账号和密码的正确性
        UserService userService = new UserService ();
        User user = userService.userLoginService (new User (userName,passWord));
        if (null == user) {
            System.out.println ("登录失败，账号或密码错误");
            //实现服务器跳转 共享request 和response对象
            request.setAttribute ("error","登录失败，账号或密码错误");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher ("login1.jsp");
            requestDispatcher.forward (request,response);
        } else {
            System.out.println ("登录成功，欢迎使用");
            //将登录成功的用户信息放入session实现多个请求的共享
            request.getSession ().setAttribute ("user",user);
            // 通过服务器跳转的方式 实现内部Servlet之间的跳转
            RequestDispatcher requestDispatcher = request.getRequestDispatcher ("/student.jsp");
            requestDispatcher.forward (request,response);


        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost (request, response);
    }
}
